from mcp import ClientSession, StdioServerParameters, types
import asyncio
import os

# AnyUrl用于资源URL的类型校验
from pydantic import AnyUrl

from mcp.client.stdio import stdio_client


def print_call_result(tag: str, result: types.CallToolResult) -> None:
    readable_parts: list[str] = []
    for block in result.content:
        if isinstance(block, types.TextContent):
            readable_parts.append(block.text)
    printable_text = "|".join(readable_parts) if readable_parts else "<no text content>"
    structured = getattr(result, "structuredContent", None)
    print(f"[{tag}] text=", printable_text)
    print(f"[{tag}] structured=", structured)


async def main() -> None:
    base_dir = os.path.dirname(os.path.abspath(__file__))
    server_path = os.path.join(base_dir, "server.py")
    server_params = StdioServerParameters(command="python", args=[server_path], env={})
    async with stdio_client(server_params) as (read, write):
        async with ClientSession(read, write) as session:
            await session.initialize()
            tools = await session.list_tools()
            print("[Tools]", [t.name for t in tools.tools])

            result = await session.call_tool("get_weather", {"city": "beijing"})
            print_call_result("get_weather", result)

            result = await session.call_tool("get_location", {"address": "天安门"})
            print_call_result("get_location", result)

            result = await session.call_tool("get_statistics", {"datatype": "scores"})
            print_call_result("get_statistics", result)
            result = await session.call_tool("get_user", {})
            print_call_result("get_user", result)
            result = await session.call_tool("get_temperature", {})
            print_call_result("get_temperature", result)

            result = await session.call_tool("list_cities", {})
            print_call_result("list_cities", result)

            result = await session.call_tool("get_config", {})
            print_call_result("get_config", result)

            result = await session.call_tool("unstructured_message", {})
            print_call_result("unstructured_message", result)


if __name__ == "__main__":
    asyncio.run(main())
